package com.controller;

import com.entity.Blog;
import com.entity.Blogger;
import com.lucene.BlogIndex;
import com.service.BlogService;
import com.service.BloggerService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 博客Controller层
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/blog")
public class BlogController {

    @Resource
    private BlogService blogService;
    @Resource
    public BloggerService bloggerService;

    private BlogIndex blogIndex = new BlogIndex();

    @RequestMapping("/details/{id}")
    public ModelAndView details(@PathVariable("id") Integer id, HttpServletRequest request){
        ModelAndView mav=new ModelAndView();
        Blog blog = blogService.findBlogById(id);
        mav.addObject("blog",blog);
        blog.setClickHit(blog.getClickHit()+1);
        blogService.updateBlog(blog);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("blogId", blog.getId());
        System.out.println("取得的bloggerId:"+blog.getBloggerId());
        Blogger blogger=bloggerService.getByUserId(blog.getBloggerId());
        System.out.println(blogger);
        mav.addObject("pageCode", this.getPageCode(blogService.selectLastBlog(id), blogService.selectNextBlog(id), request.getServletContext().getContextPath()));
        mav.addObject("pageTitle", blog.getTitle()+"——CV博客系统");
        mav.addObject("mainPage", "/foreground/blog/view.jsp");
        mav.addObject("blogger",blogger);
        mav.setViewName("/pages/blogg/mainTemp");
        return mav;
    }

    /**
     * 获取上一篇博客和下一篇博客
     * @return
     */
    private String getPageCode(Blog lastBlog,Blog nextBlog,String projectContext){
        StringBuffer pageCode=new StringBuffer();
        if(lastBlog==null || lastBlog.getId()==null){
            pageCode.append("<p>上一篇：无</p>");
        }else{
            pageCode.append("<p>上一篇：<a href='"+projectContext+"/blog/details/"+lastBlog.getId()+".htm'>"+lastBlog.getTitle()+"</a></p>");
        }

        if(nextBlog==null || nextBlog.getId()==null){
            pageCode.append("<p>下一篇：无</p>");
        }else{
            pageCode.append("<p>下一篇：<a href='"+projectContext+"/blog/details/"+nextBlog.getId()+".htm'>"+nextBlog.getTitle()+"</a></p>");
        }
        return pageCode.toString();
    }

    /**
     *  lucene分页
     * @throws Exception
     */
    @RequestMapping("/q")
    public ModelAndView search(@RequestParam(value = "q", required = false, defaultValue = "") String q, @RequestParam(value = "page", required = false, defaultValue = "1") String page,
                               HttpServletRequest request) throws Exception {
        /**
         * 关于查询之后的分页我采用的是每次分页发起的请求都是将所有的数据查询出来，
         * 具体是第几页再截取对应页数的数据，典型的拿空间换时间的做法，
         */
        ModelAndView model = new ModelAndView();
        List<Blog> blogList = blogIndex.searchBlog(q);
        Integer toIndex = blogList.size() >= Integer.parseInt(page) * 10 ? Integer.parseInt(page) * 10 : blogList.size();
        List<Blog> blogList1 = blogList.subList((Integer.parseInt(page) - 1) * 10, toIndex);
        model.addObject("blogList",blogList1);
        model.addObject("pageTitle", "搜索关键字为'" + q + "'结果页面");
        model.addObject("pageCode",this.genUpAndDownPageCode(Integer.parseInt(page), blogList1.size(), q, 10, request.getServletContext().getContextPath()));
        model.addObject("mainPage", "/foreground/blog/result.jsp");
        model.addObject("q", q);
        model.addObject("resultCount",blogList.size());//搜索到的记录数
        model.setViewName("/pages/blogg/mainTemp");
        return model;
    }
    /**
     * 查询之后的分页
     * @param page
     * @param totalNum
     * @param q
     * @param pageSize
     * @param projectContext
     * @return
     */
    private String genUpAndDownPageCode(int page,Integer totalNum,String q,Integer pageSize,String projectContext){
        long totalPage=totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
        StringBuffer pageCode=new StringBuffer();
        if(totalPage==0){
            return "";
        }else{
            pageCode.append("<nav>");
            pageCode.append("<ul class='pager' >");
            if(page>1){
                pageCode.append("<li><a href='"+projectContext+"/q?page="+(page-1)+"&q="+q+"'>上一页</a></li>");
            }else{
                pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
            }
            if(page<totalPage){
                pageCode.append("<li><a href='"+projectContext+"/q?page="+(page+1)+"&q="+q+"'>下一页</a></li>");
            }else{
                pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");
            }
            pageCode.append("</ul>");
            pageCode.append("</nav>");
        }
        return pageCode.toString();
    }
}
